package com.topnav.mc.admin.controller;

import com.alibaba.fastjson2.JSONObject;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.text.impl.DefaultTextCreator;
import com.js.lib.result.Result;
import com.topnav.mc.config.CalculationTextCreator;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ErrorResultUtil;
import com.topnav.mc.uitls.IdUtils;
import com.topnav.mc.uitls.RedisUtil;
import com.topnav.mc.uitls.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 验证码接口
 * @Author: kenny
 * @Date: 2024/1/5 15:01
 */
@RestController
@CrossOrigin
@RequestMapping("verify/code")
public class VerifyCodeController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Resource
    private CalculationTextCreator calculationTextCreator;

    @Resource
    private VerifyCodeUtil verifyCodeUtil;

    //获取验证码,并返回base64
    @GetMapping("/get")
    public Result getVerifyCode() throws IOException {

        String[] txt = calculationTextCreator.getText().split("@");
        BufferedImage image=defaultKaptcha.createImage(txt[0]);

        ByteArrayOutputStream outputStream=null;
        try{
            outputStream=new ByteArrayOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            //注意：JDK9 之后不支持这种写法，需要使用Base64.Encoder encoder=Base64.getEncoder();
            BASE64Encoder encoder=new BASE64Encoder();

            String base64=encoder.encode(outputStream.toByteArray());
            String captchaBase64 = "data:image/jpeg;base64," + base64;
            captchaBase64 = captchaBase64.replace("\r\n","");

            String uuid = IdUtils.getIdByUUID();
            JSONObject json = new JSONObject();
            json.put("loginSession",uuid);
            json.put("expire",verifyCodeUtil.getExpire());
            json.put("success",txt[1]);
            verifyCodeUtil.save(uuid,json);
            //code 超时时间，msg=id,data=base64图片

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("expireSec",Integer.valueOf(String.valueOf(verifyCodeUtil.getExpire())));
            resultMap.put("uuid",uuid);
            resultMap.put("image",captchaBase64.replace("\r\n",""));
            return Result.ok(resultMap);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (outputStream != null){
                outputStream.close();
            }
        }
        return ErrorResultUtil.result (ExceptionMsg.ERROR_AUTHENTICATION_GET_VERIFYCODE_FAILED);

    }
}
